package cn.edu.njupt.post.async.handler;

import cn.edu.njupt.post.async.EventHandler;
import cn.edu.njupt.post.async.EventModel;
import cn.edu.njupt.post.async.EventType;
import cn.edu.njupt.post.model.EntityType;
import cn.edu.njupt.post.model.Message;
import cn.edu.njupt.post.model.User;
import cn.edu.njupt.post.service.MessageService;
import cn.edu.njupt.post.service.UserService;
import cn.edu.njupt.post.util.OtherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class FollowHandler implements EventHandler {
    @Autowired
    MessageService messageService;

    @Autowired
    UserService userService;

    @Override
    public void doHandle(EventModel model) {
        Message message = new Message();
        int fromId = model.getActorId();
        int toId = model.getEntityOwnerId();
        message.setFromId(fromId)
                .setToId(toId)
                .setCreatedDate(new Date());
        User user = userService.getUser(model.getActorId());

        if (model.getEntityType() == EntityType.ENTITY_POST) {
            message.setContent("用户" + user.getName()
                    + "关注了你的问题");
            message.setLink("/post/" + model.getEntityId());
        } else if (model.getEntityType() == EntityType.ENTITY_USER) {
            message.setContent("用户" + user.getName()
                    + "关注了你");
            message.setLink("/user/" + model.getActorId());
        }
        message.setConversationId(fromId < toId ? String.format("%d_%d", fromId, toId) : String.format("%d_%d", toId, fromId));
        messageService.addMessage(message);
    }

    @Override
    public List<EventType> getSupportEventTypes() {
        return Arrays.asList(EventType.FOLLOW);
    }
}
